import tkinter as tk
from tkinter import filedialog, scrolledtext
from PIL import Image, ImageTk
import numpy as np
import tensorflow as tf


model = tf.keras.models.load_model('dataset/garbage_classification_model.h5')

class GarbageClassification():
    def __init__(self,win):
        self.win=win
        self.win.title('蚌埠市龙子湖小区垃圾分类系统')
        self.win.geometry("811x707")
        # 占据整个窗口的画布
        self.canvas = tk.Canvas(
                            self.win,
                            bg = "#000000",
                            height = 707,
                            width = 811,
                            bd = 0,
                            highlightthickness = 0,  #这可以使Canvas看起来像是无缝集成到其父容器中
                            relief = "ridge")           
        self.canvas.place(x = 0, y = 0)
        # 画布左边区域
        self.canvas.create_rectangle(
                                    0.0,
                                    0.0,
                                    501.0,
                                    707.0,
                                    fill="#987057",
                                    outline="")     # 设置边框的颜色
        # 画布右边区域
        self.canvas.create_rectangle(
                                    501.0,
                                    0.0,
                                    811.0,
                                    707.0,
                                    fill="#EAE0D6",
                                    outline="")     # 设置边框的颜色为""，可以避免绘制的矩形边框有黑边
        # 显示图片区域
        self.canvas.create_rectangle(
                                    70.0,
                                    80.0,
                                    431.0,
                                    332.0,
                                    fill="#D9D9D9",
                                    outline="")         # 必须设置为""，否则创建的矩形有黑边
        # 显示识别结果区域
        self.canvas.create_rectangle(
                                    70.0,
                                    471.0,
                                    382.0,
                                    620.0,
                                    fill="#D9D9D9",
                                    outline="")         #必须设置为""，否则创建的矩形有黑边
        # 输出识别结果的Text
        self.result_text=tk.Text(self.canvas,font=('System',18,'bold'),fg='black',bg='#D9D9D9',state='disabled')
        self.result_text.place(x=70.0,y=471.0,width=312,height=149)
        # 文字"识别结果"
        self.canvas.create_text(
                                35.0,
                                394.0,
                                anchor="nw",
                                text="识别结果",
                                fill="#000000",
                                font=("华文行楷", 36 * -1))
        # 下划线
        self.canvas.create_line(
                                52.0,
                                449.0,
                                101.0,
                                449.0,
                                fill="#FFFFFF",
                                width=2)
        # "上传图片"按钮
        button_3_img=Image.open('image/button_3.png')
        button_image_3 = ImageTk.PhotoImage(button_3_img)
        self.button_3 = tk.Button(
                               image=button_image_3,
                               borderwidth=0,
                               highlightthickness=0,
                               command=self.upload_image,
                               relief="flat")
        self.button_3.image=button_image_3     # 特别注意，在类内要想显示图片，必须对控件的image属性进行重新赋值，否则图片会显示为一片空白
        self.button_3.place(
                            x=536.0,
                            y=114.0,
                            width=241.0,
                            height=71.0)
        # "开始识别"按钮
        button_2_img=Image.open('image/button_2.png')
        button_image_2 = ImageTk.PhotoImage(button_2_img)
        self.button_2 = tk.Button(
                        image=button_image_2,
                        borderwidth=0,
                        highlightthickness=0,
                        command=self.begin_classify,
                        relief="flat")
        self.button_2.image=button_image_2      # 特别注意，image得重新赋值，否则图片会显示为一片空白
        self.button_2.place(
                       x=536.0,
                       y=224.0,
                       width=241.0,
                       height=71.0)
        # "退出"按钮
        button_1_img=Image.open('image/button_1.png')
        button_image_1 = ImageTk.PhotoImage(button_1_img)
        self.button_1 = tk.Button(
                          image=button_image_1,
                          borderwidth=0,
                          highlightthickness=0,
                          command=self.win.destroy,
                          relief="flat")
        self.button_1.image=button_image_1      #对Button的image属性进行重新赋值
        self.button_1.place(
                        x=581.0,
                        y=510.0,
                        width=141.0,
                        height=71.0)
        self.win.resizable(False, False)            #设置窗口的大小不能随意改变

        # 以上为前端界面设计
        # 下面为后端设计

    def upload_image(self):
        #首先清除上一次文本框中的识别结果
        self.result_text['state']='normal'
        self.result_text.delete(1.0,"end")
        self.result_text['state']='disabled'
        # 打开文件对话框，选择图片文件
        self.file_path = filedialog.askopenfilename(title='请选择要上传的图片',filetypes=[("图像文件", "*.jpg;*.jpeg;*.png;*.gif")],initialdir='./素材image')
        if self.file_path:
        # 加载并显示所选图片
            image = Image.open(self.file_path)
            image = image.resize((361, 252))  # 调整大小以适应界面
            photo = ImageTk.PhotoImage(image)
            self.image_label=tk.Label(self.canvas,image=photo)
            self.image_label.image = photo
            self.image_label.place(x=70.0,y=80.0,width=361,height=252)

    def begin_classify(self):
        # 对上传的图片进行分类
        predicted_class = self.classify_image(self.file_path)
        if predicted_class == "硬纸板" or "玻璃" or "金属" or "纸张":
            Judge_result = "可回收垃圾"
        elif predicted_class == "玻璃":
            Judge_result = "不可回收垃圾"
        self.result_text['state']='normal'
        self.result_text.insert('1.0',
                                f"据预测，该物体材质为：{predicted_class}\n\n此物体大概率属于：{Judge_result}\n\n注意：此识别结果仅供参考，请以当地指定的标准为准！\n")
        self.result_text['state']='disabled'

    def classify_image(self, image_path):
        # 加载图片并进行预处理
        img = Image.open(image_path)
        img = img.resize((500, 400))  # 调整大小
        img = np.array(img) / 255.0  # 归一化
        img = np.expand_dims(img, axis=0)
        # 进行分类预测
        predictions = model.predict(img)
        class_labels = ['硬纸板', '玻璃', '金属', '纸张','塑料']
        predicted_class_index = np.argmax(predictions)
        predicted_label = class_labels[predicted_class_index]
        return predicted_label


